package cn.bone.motan.jingzhouArea.server;

import cn.bone.motan.common.MoRequest;
import cn.bone.motan.common.MoResponse;
import cn.bone.motan.demo1.api.GatewayApi;
import cn.bone.motan.jingzhouArea.data.RouteData;
import cn.bone.motan.jingzhouArea.data.TempConfig;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by MD-01 on 2017/3/15.
 */
@Service
public class RouteService {

    @Resource(name="gateway")
    private GatewayApi gatewayApi;

    public MoResponse getRoutes(MoRequest request){

        if(request==null || StringUtils.isEmpty(request.getTo())){
            return MoResponse.error("参数不能为空");
        }
        String sign = request.getTo();

        //访问本域
        if(TempConfig.me.getSign().equals(sign)){
            RouteData routeData = TempConfig.routeData;
            return MoResponse.ok(JSON.toJSONString(routeData));
        }


        //不属于本域,判断请求是否属于下属gateway
        List<TempConfig.Area> downAreaes = TempConfig.downAreaes;
        TempConfig.Area target = null;
        for(TempConfig.Area area : downAreaes){
            if(sign.contains(area.getSign())){
                target = area;
                break;
            }
        }
        if(target==null){
            return MoResponse.error("没有对应的sign");
        }
        request.setToGateWay(target.getSign());
        //把消息转发到gateway
        return gatewayApi.execute(request);
    }
}
